// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  var {
    op,
    _openid
  } = event

  switch (op) {
    case 'openBoxRecord':
      return openBoxRecord();
      break;
    case 'myHomeRecord':
      return myHomeRecord();
      break;
    case 'delRecord':
      return delRecord();
      break;
  }

  //开宝箱的消息
  async function openBoxRecord() {
    let records = await db.collection('Record')
      .aggregate()
      .match({
        'content.op': _.eq('openBox').or(_.eq('hideBox'))
      })
      .sort({
        createTime: -1
      })
      .lookup({
        from: 'User',
        localField: '_openid',
        foreignField: '_openid',
        as: 'user',
      }).limit(20).end()

    let list = records.list
    for (let i = 0; i < list.length; i++) {
      list[i].avatar = list[i].user[0].avatar
      let nickname = list[i].user[0].nickname ? list[i].user[0].nickname : '匿名'
      nickname = nickname.substr(0, 2) + "..."

      switch (list[i].content.op) {
        case 'openBox':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 寻获了 " + list[i].content.treasureAmount + " 个宝石"
          break;
        case 'hideBox':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 藏了 " + list[i].content.treasureAmount + " 个宝石"
          break;
      }


      delete list[i].user
      delete list[i].createTime
      delete list[i]._openid
      delete list[i]._id
    }

    return list
  }

  //我家被光顾的消息
  async function myHomeRecord() {
    let records = await db.collection('Record')
      .aggregate()
      .match({
        'content.op': _.eq('getIn').or(_.eq('robGold')).or(_.eq('robTreasure')).or(_.eq('hit')).or(_.eq('feed')).or(_.eq('giveGold')),
        'content._openid': _openid ? _openid : wxContext.OPENID
      })
      .sort({
        createTime: -1
      })
      .lookup({
        from: 'User',
        localField: '_openid',
        foreignField: '_openid',
        as: 'user',
      }).limit(10).end()

    let list = records.list
    for (let i = 0; i < list.length; i++) {
      list[i].avatar = list[i].user[0].avatar
      let nickname = list[i].user[0].nickname ? list[i].user[0].nickname : '匿名'
      let owner = _openid ? 'TA' : '你'
      //   nickname = nickname.substr(0, 1) + "*" + nickname.substr(nickname.length - 1, 1)

      switch (list[i].content.op) {
        case 'getIn':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 到访" + owner + "家 "
          break;
        case 'robGold':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 抢了" + owner + " " + list[i].content.gold + " 金币"
          break;
        case 'robTreasure':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 抢了" + owner + " " + list[i].content.treasureAmount + " 颗宝石"
          break;
        case 'hit':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 殴打了" + owner + "的精灵 "
          break;
        case 'feed':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 帮" + owner + "喂了精灵 "
          break;
        case 'giveGold':
          list[i].content = nickname + " " + sinceToday(list[i].createTime) + " 送了你 " + list[i].content.gold + " 金币"
          break;
      }



      delete list[i].user
      delete list[i].createTime
      // delete list[i]._openid
      delete list[i]._id
    }

    return list
  }
  async function delRecord() {
    let records = await db.collection('Record')
     
      .where({
        'content.op': _.eq('getIn').or(_.eq('robGold')).or(_.eq('robTreasure')).or(_.eq('hit')).or(_.eq('feed')).or(_.eq('giveGold')),
        'content._openid': wxContext.OPENID
      })
      .orderBy('createTime', 'desc')
      .limit(10)
      .remove()
    return records
  }
  /**
   * 距离今天已经多少天
   */
  function sinceToday(date, end = null) {
    var dateBegin = new Date(date); //将-转化为/，使用new Date
    var dateEnd = end == null ? new Date() : new Date(end); //获取当前时间
    var dateDiff = dateEnd.getTime() - dateBegin.getTime(); //时间差的毫秒数
    var dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
    var leave1 = dateDiff % (24 * 3600 * 1000) //计算天数后剩余的毫秒数
    var hours = Math.floor(leave1 / (3600 * 1000)) //计算出小时数
    //计算相差分钟数
    var leave2 = leave1 % (3600 * 1000) //计算小时数后剩余的毫秒数
    var minutes = Math.floor(leave2 / (60 * 1000)) //计算相差分钟数
    //计算相差秒数
    var leave3 = leave2 % (60 * 1000) //计算分钟数后剩余的毫秒数
    var seconds = Math.round(leave3 / 1000);
    var timesString = '';

    if (dayDiff != 0) {
      timesString = dayDiff + '天前'
      //  timesString = dateBegin.getFullYear().toString() + "-" + (dateBegin.getMonth() + 1).toString() + "-"+ dateBegin.getDate().toString();
    } else if (dayDiff == 0 && hours != 0) {
      timesString = hours + '小时前';
    } else if (dayDiff == 0 && minutes != 0) {
      timesString = minutes + '分钟前';
    } else {
      timesString = '刚刚';
    }

    return timesString;
  }
}